package canraid.agent.implementations;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.os.Handler;
import android.os.Message;
import canraid.agent.Cagent;
import canraid.agent.Iagent;
import canraid.debug.Level;
import canraid.debug.Logger;

public class FileAgent extends Cagent {
	private final int NAME=canraid.gen.R.id.buttonFile;
	
	private File file=null;
	private FileWriter filewriter = null;
	private BufferedWriter fo = null;
	private String path=null;
	private String nameFile=null;
	private Handler[] handlers=null;
	

	public FileAgent(String path, String nameFile) {
		super(1000);
		this.path=path;
		this.nameFile=nameFile;
		
        Logger.setLog(this,Level.ASSERT,"FileAgent().");
	}
	
	public int getAgentName(){
		return NAME;
	}
	
	protected boolean __setup(){
        Logger.setLog(this,Level.ASSERT,"__setup().");
        
        if (path==null || nameFile==null){
            Logger.setLog(this,Level.ERROR,"__setup(). Path("+path+") or nameFile("+nameFile+") not valid.");
            return false;
        }
        
        handlers = getPoolExternalHandlers();
        
		file=new File(path+ File.separator + nameFile);
		try {
			filewriter = new FileWriter(file);
			fo = new BufferedWriter(filewriter);    
		} 
		catch (IOException e) {
            Logger.setLog(this,Level.ERROR,"__setup(). Creation File failed. ERROR:"+e.getMessage());
            if (fo!=null){
    			try {
    				fo.flush();
    				fo.close();
    			} 
    			catch (IOException e1) {}
            }
            return false;
		}
		return true;
	}
	
	protected boolean __loop(){
        Logger.setLog(this,Level.ASSERT,"__loop().");
        
		try {
			int bytesOutput=getQueueLength();
			
			if (bytesOutput>0){
				byte[] bufferOutput=__getCopyBufferOutput(true);
				bytesOutput=bufferOutput.length;
				
				for (int k=0;k<bytesOutput;k++)
					fo.write(bufferOutput[k]);
				
				fo.flush();
		        Logger.setLog(this,Level.INFO,"__loop(). Writing on file --> "+bytesOutput+" bytes");
			}
			
			for(int h=0; h<handlers.length;h++){
        		handlers[h].obtainMessage(Iagent.SIZE_QUEUE_FILE, bytesOutput).sendToTarget();
		        Logger.setLog(this,Level.INFO,"__loop(). Sending value len="+bytesOutput+" to Handler("+handlers[h].toString()+")");
        	}
			return true;
		}
		catch(Exception e){
            Logger.setLog(this,Level.ERROR,"__loop(). Running failed. Error("+e.getMessage()+")");
            if (fo!=null){
    			try {
    				fo.flush();
    				fo.close();
    			} 
    			catch (IOException e1) {}
            }
            return false;
		}
	}
		
	public void close(){
		Logger.setLog(this,Level.ASSERT,"close().");
		stopPolling();
		
		if (fo!=null){
			try {
				fo.flush();
				fo.close();
			} 
			catch (IOException e) {}
			finally{
				fo=null;
			}
		}
	}
	
	protected boolean __implementMyHandler(Message msg) {
		Logger.setLog(this,Level.ASSERT,"__implementMyHandler().");
		
		switch (msg.what) {
        case Iagent.FROM_BT:
        	if (msg.arg1>0){
	        	byte[] data= (byte[]) msg.obj;
	        	byte[] dataBT=new String("CAN("+data.length+"): "+new String(data)+System.getProperty("line.separator")).getBytes();
	        	Logger.setLog(this,Level.INFO,"__implementMyHandler(). FROM_BT");
	        	pushInQueue(dataBT);
        	}
        	break;
        case Iagent.FROM_NTW:
        	if (msg.arg1>0){
	        	byte[] data= (byte[]) msg.obj;
	        	byte[] dataNTW=new String("NTW("+data.length+"): "+new String(data)+System.getProperty("line.separator")).getBytes();
	        	Logger.setLog(this,Level.INFO,"__implementMyHandler(). FROM_NTW");
	        	pushInQueue(dataNTW);
        	}
        	break;
        case Iagent.FROM_TEXT:
        	if (msg.arg1>0){
	        	byte[] data= (byte[]) msg.obj;
	        	byte[] dataTXT=new String("YOU("+data.length+"): "+new String(data)+System.getProperty("line.separator")).getBytes();
	        	Logger.setLog(this,Level.INFO,"__implementMyHandler(). FROM_TEXT");
	        	pushInQueue(dataTXT);
        	}
        	break;
        default:
        	return false;
        }
		return true;
	}

}
